package com.syf.kit.core.ds.spi.impl;

import com.syf.kit.core.ds.config.PooledRdsDbConfig;
import com.syf.kit.core.ds.spi.RdsDataSourceFactory;
import com.syf.kit.enums.RDSType;
import org.apache.commons.dbcp2.BasicDataSource;

import javax.sql.DataSource;

public class SyfDbcpDataSourceFactory implements RdsDataSourceFactory {
    private final String dataSourceName = "DBCP";

    @Override
    public DataSource buildPooledDataSource(RDSType rdsType, PooledRdsDbConfig dbConfig) {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(rdsType.getDriveClassName());
        dataSource.setUrl(dbConfig.getJdbcUrl());
        dataSource.setUsername(dbConfig.getDbUser());
        dataSource.setPassword(dbConfig.getDbPassword());
        dataSource.setInitialSize(dbConfig.getInitSize());
        dataSource.setMinIdle(dbConfig.getMinIdleSize());
        dataSource.setMaxIdle(dbConfig.getMaxIdleSize());
        dataSource.setMaxTotal(dbConfig.getMaxSize());
        dataSource.setMaxWaitMillis(Long.parseLong(dbConfig.getMaxWaitMs()));

        dataSource.setValidationQuery(dbConfig.getValidateSql());
        dataSource.setTestOnBorrow(dbConfig.isTestOnBorrow());
        dataSource.setTestOnReturn(dbConfig.isTestOnReturn());
        dataSource.setTestWhileIdle(dbConfig.isTestWhileIdle());

        dataSource.setTimeBetweenEvictionRunsMillis(dbConfig.getTimeBetweenEvictionRunsMs());
        dataSource.setMinEvictableIdleTimeMillis(dbConfig.getMinEvictableIdleTimeMs());
        dataSource.setNumTestsPerEvictionRun(8);
        return dataSource;
    }

    @Override
    public String getDBPoolName() {
        return dataSourceName;
    }
}
